package com.fhminyi.GUI;

import com.fhminyi.dao.ProductDao;
import com.fhminyi.model.Product;
import com.fhminyi.model.User;
import com.fhminyi.util.ImageUploadSelector;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

public class EditProductDetailFrame extends JFrame {
    private User currentUser;
    private Product product;
    private JTextField nameField;
    private JTextArea descriptionArea;
    private JTextField priceField;
    private JTextField stockField;
    private JTextField categoryField;
    private JButton submitButton;
    private JButton uploadButton;
    private ImageUploadSelector imageUploadSelector;
    private JLabel imageLabel;

    public EditProductDetailFrame(User currentUser, Product product) {
        this.currentUser = currentUser;
        this.product = product;
        setTitle("编辑商品详情");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(7, 2));

        JLabel nameLabel = new JLabel("商品名称:");
        nameField = new JTextField(product.getProductName());

        JLabel descriptionLabel = new JLabel("描述:");
        descriptionArea = new JTextArea(product.getDescription());
        descriptionArea.setLineWrap(true);
        JScrollPane descriptionScrollPane = new JScrollPane(descriptionArea);

        JLabel priceLabel = new JLabel("价格:");
        priceField = new JTextField(String.valueOf(product.getPrice()));

        JLabel stockLabel = new JLabel("库存:");
        stockField = new JTextField(String.valueOf(product.getStock()));

        JLabel categoryLabel = new JLabel("类别:");
        categoryField = new JTextField(product.getCategory());

        imageLabel = new JLabel();
        try {
            ImageIcon icon = new ImageIcon(product.getImageLocation());
            Image img = icon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH); // 调整图片大小
            ImageIcon scaledIcon = new ImageIcon(img);
            imageLabel.setIcon(scaledIcon);
            imageLabel.setHorizontalAlignment(JLabel.CENTER); // 图片居中显示
        } catch (Exception e) {
            imageLabel.setText("无法加载图片");
        }

        uploadButton = new JButton("上传图片");
        uploadButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                imageUploadSelector.showFileChooser(EditProductDetailFrame.this);
                File selectedFile = imageUploadSelector.getSelectedFile();
                if (selectedFile != null) {
                    try {
                        ImageIcon icon = new ImageIcon(selectedFile.getAbsolutePath());
                        Image img = icon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH); // 调整图片大小
                        ImageIcon scaledIcon = new ImageIcon(img);
                        imageLabel.setIcon(scaledIcon);
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(EditProductDetailFrame.this, "无法加载图片", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        submitButton = new JButton("提交");
        submitButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        String name = nameField.getText().trim();
        String description = descriptionArea.getText().trim();
        String priceStr = priceField.getText().trim();
        String stockStr = stockField.getText().trim();
        String category = categoryField.getText().trim();

        if (name.isEmpty() || description.isEmpty() || priceStr.isEmpty() || stockStr.isEmpty() || category.isEmpty()) {
            JOptionPane.showMessageDialog(EditProductDetailFrame.this, "所有字段都必须填写", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            double price = Double.parseDouble(priceStr);
            int stock = Integer.parseInt(stockStr);

            product.setProductName(name);
            product.setDescription(description);
            product.setPrice(price);
            product.setStock(stock);
            product.setCategory(category);

            // 添加空值检查
            if (imageUploadSelector != null) {
                File selectedFile = imageUploadSelector.getSelectedFile();
                if (selectedFile != null) {
                    product.setImageLocation(selectedFile.getAbsolutePath());
                    imageUploadSelector.uploadProductImage(product);
                }
                // 如果没有选择新图片，则保留原来的图片路径
                else {
                    product.setImageLocation(product.getImageLocation());
                }
            } else {
                // 处理 imageUploadSelector 为 null 的情况
                product.setImageLocation(product.getImageLocation());
            }

            ProductDao productDao = new ProductDao();
            productDao.updateProduct(product);

            JOptionPane.showMessageDialog(EditProductDetailFrame.this, "商品更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            dispose();
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(EditProductDetailFrame.this, "价格和库存必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
        } catch (SQLException | IOException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(EditProductDetailFrame.this, "商品更新失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
});


        panel.add(nameLabel);
        panel.add(nameField);
        panel.add(descriptionLabel);
        panel.add(descriptionScrollPane);
        panel.add(priceLabel);
        panel.add(priceField);
        panel.add(stockLabel);
        panel.add(stockField);
        panel.add(categoryLabel);
        panel.add(categoryField);
        panel.add(imageLabel);
        panel.add(uploadButton);
        panel.add(submitButton);

        add(panel);
    }
}
